package LeetCode.leetcode199;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

class Solution {
    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        Queue<TreeNode> queue = new LinkedList<>();
        TreeNode tmp;
        if (root == null)
            return res;

        queue.offer(root);
        while (!queue.isEmpty()){
            List<Integer> lines = new ArrayList<>();
            int length = queue.size();
            while (length > 0){
                tmp = queue.poll();
                assert tmp != null;
                lines.add(tmp.val);
                if (tmp.left != null)
                    queue.offer(tmp.left);
                if (tmp.right != null)
                    queue.offer(tmp.right);
                length--;
            }
            res.add(lines.get(lines.size()-1));
        }
        return res;
    }
}


class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

